#include "ItemEditForm.h"
#include "ui_ItemEditForm.h"

#include <d20.h>

#include <QTimer>

using namespace d20;

ItemEditForm::ItemEditForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ItemEditForm)
{
    ui->setupUi(this);
    ui->typeLabel->setText("Select Item");
}

ItemEditForm::~ItemEditForm()
{
    delete ui;
}


void ItemEditForm::setItem(Item* item)
{
    disconnect(this, SLOT(onChanged()));

    m_item = item;
    if (m_item.isNull())
    {
        ui->typeLabel->setText("Select Item");
        return;
    }

    onChanged();
    connect(m_item.data(), SIGNAL(sigChanged()), this, SLOT(onChanged()));

    ui->nameLineEdit->setSelection(0, ui->nameLineEdit->text().length());
    ui->nameLineEdit->setFocus();

    ui->typeLabel->setText(d20::typeToName(m_item->type().toInt()));
}


Item* ItemEditForm::item() const
{
    return m_item.data();
}


void ItemEditForm::onChanged()
{
    if (m_item.isNull()) return;

    ui->nameLineEdit->setText(m_item->name());
    ui->descTextEdit->setPlainText(m_item->desc().toUtf8());
}

void ItemEditForm::on_nameLineEdit_returnPressed()
{
    updateItem();
}

void ItemEditForm::on_nameLineEdit_lostFocus()
{
    on_nameLineEdit_returnPressed();
}



void ItemEditForm::on_typeComboBox_currentIndexChanged(int index)
{
    if (m_item.isNull()) return;

    m_item->setType(index);
}

void ItemEditForm::on_descTextEdit_textChanged()
{
    //m_item->setDesc(ui->descTextEdit->toPlainText());
}


void ItemEditForm::updateItem()
{
    if (m_item.isNull()) return;

    m_item->setName(ui->nameLineEdit->text());
}
